# coding: utf8
"""生成图表类

charts_create.py"""
import matplotlib as mpl  
mpl.use('Agg')
import matplotlib.pyplot as plt
from pylab import mpl
import random
mpl.rcParams['font.sans-serif'] = ['STKaiti'] #支持中文


def len_diff(x, y):
	return len(x) - len(y)

class ChartsCreate(object):
	"""

	创建图表
	"""

	def __init__(self):
		self.charts_title = u'图表标题--趋势图'
		self.x_title = u'X轴标题'
		self.y_title = u'Y轴标题'
		self.marker_list = ['o','v','s','p','h','H','d','D','^','<','>','+','1','2','3']
		self.mec_list = ['b','g','r','c','m','y','k']
		pass

	def __init(self):
		"""初始化图表"""
		plt.title(self.charts_title) #标题
		plt.xlabel(self.x_title) #X轴标签
		plt.ylabel(self.y_title) #Y轴标签

	def line_charts(self, x_list, y_list):
		"""

		线表
		"""
		self.__init()
		x_num_list = range(len(x_list))

		for y in y_list:
			# 用0来补充x,y列表的个数差
			diff = len_diff(x_list, y[1:])
			if diff > 0:
				y += [0] * diff

			plt.plot(x_num_list, y[1:], 
				marker=random.choice(self.marker_list), 
				mec=random.choice(self.mec_list), mfc='w', label=y[0])

		plt.xticks(x_num_list, x_list, rotation=45)
		plt.legend()  # 图标示例

	@staticmethod
	def show():
		"""

		展示
		"""
		plt.show()

	@staticmethod
	def save(file_name):
		"""

		保存
		"""
		plt.savefig(file_name)

	@staticmethod
	def close():
		"""

		关闭
		"""
		plt.close()

def example(fileName):
	"""

	例子
	"""
	import time
	x_list = []
	for i in range(6, -1, -1):
		str_time = time.strftime("%Y-%m-%d", time.localtime(time.time()-i*24*3600))
		x_list.append(str_time)
	y_list = [
				[u'我是Y1', 0.855, 0.84, 0.835, 0.815, 0.81, 0.815, 0.81],
				[u'我是Y2', 0.86,0.85,0.853,0.849,0.83,0.815, 0.81]
			]

	Chart = ChartsCreate()
	Chart.line_charts(x_list, y_list)
	# Chart.show()
	Chart.save(fileName)
	Chart.close()

if __name__ == '__main__':
	example('1.png')
